import 'package:chatgreat/bloc/free_count_bloc.dart';
import 'package:chatgreat/helper/AppUtil.dart';
import 'package:chatgreat/helper/haptic_feedback.dart';
import 'package:chatgreat/helper/upload.dart';
import 'package:chatgreat/lang/lang.dart';
import 'package:chatgreat/page/component/audio_player.dart';
import 'package:chatgreat/page/component/background_container.dart';
import 'package:chatgreat/page/component/chat/chat_share.dart';
import 'package:chatgreat/page/component/chat/file_upload.dart';
import 'package:chatgreat/page/component/chat/message_state_manager.dart';
import 'package:chatgreat/page/component/effect/glass.dart';
import 'package:chatgreat/page/component/enhanced_textfield.dart';
import 'package:chatgreat/page/component/loading.dart';
import 'package:chatgreat/page/component/theme/custom_size.dart';
import 'package:chatgreat/page/component/theme/custom_theme.dart';
import 'package:chatgreat/bloc/chat_message_bloc.dart';
import 'package:chatgreat/bloc/room_bloc.dart';
import 'package:chatgreat/bloc/notify_bloc.dart';
import 'package:chatgreat/page/component/chat/chat_input.dart';
import 'package:chatgreat/page/component/chat/chat_preview.dart';
import 'package:chatgreat/repo/model/message.dart';
import 'package:chatgreat/repo/model/misc.dart';
import 'package:chatgreat/repo/model/room.dart';
import 'package:chatgreat/repo/settings_repo.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:chatgreat/widgets/flutter_life_state/flutter_life_state.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localization/flutter_localization.dart';
import 'package:go_router/go_router.dart';
import 'package:chatgreat/repo/model/model.dart' as mm;

import '../../repo/api_server.dart';
import '../component/dialog.dart';
import 'home.dart';

class RoomChatPage extends StatefulWidget {
  final int roomId;
  final String titleName;
  final String avater;
  final MessageStateManager stateManager;
  final SettingRepository setting;

  const RoomChatPage({
    super.key,
    required this.roomId,
    required this.titleName,
    required this.avater,
    required this.stateManager,
    required this.setting,
  });

  @override
  State<RoomChatPage> createState() => _RoomChatPageState();
}

class _RoomChatPageState extends BaseLifeState<RoomChatPage> {
  final ScrollController _scrollController = ScrollController();
  final ValueNotifier<bool> _inputEnabled = ValueNotifier(true);
  final ChatPreviewController _chatPreviewController = ChatPreviewController();
  final AudioPlayerController _audioPlayerController =
      AudioPlayerController(useRemoteAPI: true);

  FreeModelCount? freeModelCount;
  List<FileUpload> selectedImageFiles = [];
  var firstLoad = true;

  final GlobalKey<ChatPreviewState> _previewPageKey = GlobalKey();
  @override
  void initState() {
    super.initState();
    // go. /room/$id/chat'
    // context.read<ChatMessageBloc>().add(ChatMessageGetRecentEvent());
    context.read<RoomBloc>().add(RoomLoadEvent(widget.roomId, cascading: true));

    _chatPreviewController.addListener(() {
      setState(() {});
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    _chatPreviewController.dispose();
    _audioPlayerController.dispose();
    super.dispose();
  }

  @override
  void onResumed() {
    if ((AppUtil().touristLoginModel?.isVip ?? 0) != 1) {
      context.read<FreeCountBloc>().add(FreeCountReloadEvent(model: 'great'));
    }
    context.read<ChatMessageBloc>().add(ChatMessageGetRecentEvent());
    super.onResumed();
  }

  @override
  Widget build(BuildContext context) {
    final customColors = Theme.of(context).extension<CustomColors>()!;

    return BackgroundContainer(
      setting: widget.setting,
      child: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/bg1.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: Scaffold(
          appBar: _buildAppBar(context, customColors),
          backgroundColor: Colors.transparent,
          body: _buildChatComponents(customColors),
        ),
      ),
    );
  }

  mm.Model? roomModel;

  Widget _buildChatComponents(CustomColors customColors) {
    return BlocConsumer<RoomBloc, RoomState>(
      listenWhen: (previous, current) =>
          current is RoomLoaded && current.room.id == widget.roomId,
      listener: (context, state) {
        if (state is RoomLoaded && state.cascading) {
          // 加载免费使用次数
          if ((AppUtil().touristLoginModel?.isVip ?? 0) != 1) {
            context
                .read<FreeCountBloc>()
                .add(FreeCountReloadEvent(model: 'great'));
          }
        }
      },
      buildWhen: (previous, current) =>
          current is RoomLoaded && current.room.id == widget.roomId,
      builder: (context, room) {
        if (room is RoomLoaded) {
          return SafeArea(
            top: false,
            bottom: true,
            child: Column(
              children: [
                // if (Ability().showGlobalAlert)
                //   const GlobalAlert(pageKey: 'chat'),
                // 语音输出中提示
                // if (showAudioPlayer)
                //   EnhancedAudioPlayer(
                //     controller: _audioPlayerController,
                //     loading: audioLoadding,
                //   ),
                // 聊天内容窗口
                Expanded(
                  child: Stack(
                    fit: StackFit.expand,
                    children: [
                      _buildChatPreviewArea(room, customColors,
                          _chatPreviewController.selectMode),
                      // if (!_inputEnabled.value)
                      //   Positioned(
                      //     bottom: 10,
                      //     width: MediaQuery.of(context).size.width,
                      //     child: Center(
                      //       child: StopButton(
                      //         label: '停止输出',
                      //         onPressed: () {
                      //           HapticFeedbackHelper.mediumImpact();
                      //           context
                      //               .read<ChatMessageBloc>()
                      //               .add(ChatMessageStopEvent());
                      //         },
                      //       ),
                      //     ),
                      //   ),
                      //语音
                      Align(
                        alignment: Alignment.centerRight,
                        child: RepaintBoundary(
                          child: Container(
                            color: Colors.transparent,
                            margin: const EdgeInsets.only(right: 8),
                            child: IconButton(
                              iconSize: 32,
                              icon: Image.asset('images/speech.png'),
                              onPressed: () {
                                // 次数判断
                                if (freeModelCount != null && freeModelCount?.leftCount != null) {
                                  if ((AppUtil().touristLoginModel?.isVip ?? 0) == 0 &&
                                      freeModelCount!.leftCount == 0) {
                                    showVipGlobalDialog(context);
                                    return;
                                  }
                                }
                                context.push('/home_speeh_chat', extra: {
                                  'name': widget.titleName,
                                  'avater': widget.avater,
                                  'roomId': widget.roomId
                                });
                              },
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
                // 聊天输入窗口
                Container(
                  decoration: const BoxDecoration(
                    color: Colors.transparent,
                  ),
                  child: BlocBuilder<FreeCountBloc, FreeCountState>(
                    builder: (context, freeState) {
                      var hintText = '请输入你的问题~';
                      if (freeState is FreeCountLoadedState &&
                          (AppUtil().touristLoginModel?.isVip ?? 0) == 0) {
                        final matched = freeState.counts.first;
                        // if (matched != null && matched.leftCount > 0) {
                        //   hintText += '（今日还可免费${matched.leftCount}次）';
                        // }
                        freeModelCount = matched;
                      }

                      return ChatInput(
                        keyIndex: 2,
                        enableNotifier: _inputEnabled,
                        onSubmit: (value) {
                          _handleSubmit(value);
                          FocusManager.instance.primaryFocus?.unfocus();
                        },
                        enableImageUpload: false,
                        onImageSelected: (files) {
                          setState(() {
                            selectedImageFiles = files;
                          });
                        },
                        selectedImageFiles: selectedImageFiles,
                        onNewChat: () => handleResetContext(context),
                        hintText: hintText,
                        onVoiceRecordTappedEvent: () {
                          _audioPlayerController.stop();
                        },
                        onAlertVipTappedEvent: () {
                          showVipGlobalDialog(context);
                        },
                        onStopGenerate: () {
                          context
                              .read<ChatMessageBloc>()
                              .add(ChatMessageStopEvent());
                        },
                      );
                    },
                  ),
                ),
              ],
            ),
          );
        } else {
          return Container();
        }
      },
    );
  }

  BlocConsumer<ChatMessageBloc, ChatMessageState> _buildChatPreviewArea(
    RoomLoaded room,
    CustomColors customColors,
    bool selectMode,
  ) {
    return BlocConsumer<ChatMessageBloc, ChatMessageState>(
      listener: (context, state) {
        if (state is ChatMessageUpdated) {
          // 聊天内容窗口滚动到底部
          if (!state.processing && _scrollController.hasClients) {
            _scrollController.animateTo(
              0,
              duration: const Duration(milliseconds: 500),
              curve: Curves.easeOut,
            );
          }

          if (state.processing && _inputEnabled.value) {
            _previewPageKey.currentState?.currentTextIndex = 0;
            _previewPageKey.currentState?.recordMessage = state.message;
            Future.delayed(const Duration(seconds: 1)).then((value) {
              _previewPageKey.currentState?.animationController.repeat();
            });
            // 聊天回复中时，禁止输入框编辑
            setState(() {
              _inputEnabled.value = false;
            });
          } else if (!state.processing && !_inputEnabled.value) {
            // 更新免费使用次数
            if (AppUtil().touristLoginModel?.isVip != 1) {
              context
                  .read<FreeCountBloc>()
                  .add(FreeCountReloadEvent(model: 'great'));
            }
            // 弹出评价
            // inAppReviewEvent();
            // 聊天回复完成时，取消输入框的禁止编辑状态
            // setState(() {
            //   _inputEnabled.value = true;
            // });
          }
        }
      },
      buildWhen: (prv, cur) => cur is ChatMessagesLoaded,
      builder: (context, state) {
        if (state is ChatMessagesLoaded) {
          final loadedMessages = state.messages as List<Message>;
          if (room.room.initMessage != null && room.room.initMessage != '') {
            var initMessage = Message(
              Role.receiver,
              room.room.initMessage!,
              serverId: room.room.serverId,
              roomId: room.room.id,
              type: MessageType.initMessage,
              id: 0,
              like: room.room.initMessageLike ?? 0,
              collection: room.room.initMessageCollect ?? 0,
            );

            var has = false;
            if (loadedMessages.isNotEmpty) {
              for (var element in loadedMessages) {
                if (element.id == 0) {
                  has = true;
                }
              }
            }
            if (!has) {
              loadedMessages.insert(0, initMessage);
            }
          }

          // 暂时不需要问题
          // if (loadedMessages.isEmpty) {
          //   return Padding(
          //     padding: const EdgeInsets.only(left: 15, right: 15, top: 10),
          //     child: EmptyPreview(
          //       examples: room.chatQuestion?.records ?? [],
          //       onSubmit: _handleSubmit,
          //     ),
          //   );
          // }

          final messages = loadedMessages.map((e) {
            final stateMessage = room.states[
                    widget.stateManager.getKey(e.roomId ?? 0, e.id ?? 0)] ??
                MessageState();
            return MessageWithState(e, stateMessage);
          }).toList();

          _chatPreviewController.setAllMessageIds(messages);

          return ChatPreview(
            // padding: _inputEnabled.value ? null : const EdgeInsets.only(bottom: 35),
            key: _previewPageKey,
            keyIndex: 2,
            messages: messages,
            scrollController: _scrollController,
            controller: _chatPreviewController,
            audioPlayerController: _audioPlayerController,
            stateManager: widget.stateManager,
            robotAvatar: const SizedBox(),
            onDeleteMessage: (id) {
              handleDeleteMessage(context, id, chatHistoryId: widget.roomId);
            },
            onResetContext: () => handleResetContext(context),
            onResentEvent: (message, index) {
              _scrollController.animateTo(0,
                  duration: const Duration(milliseconds: 500),
                  curve: Curves.easeOut);

              _handleSubmit(message.text,
                  messagetType: message.type, index: index, isResent: true);
            },
            onSpeakEvent: (message) {
              _audioPlayerController
                  .playAudioWithMessageId(message.serverId ?? 0);
            },
            onLikeEvent: (message, index) {
              context
                  .read<ChatMessageBloc>()
                  .add(ChatMessageUpdateEvent(message));
            },
            onCollectionEvent: (message, index) {
              context
                  .read<ChatMessageBloc>()
                  .add(ChatMessageUpdateEvent(message));
            },
            onReadyAnimedEvent: () {
              // 弹出评价
              // inAppReviewEvent();
              setState(() {
                _inputEnabled.value = true;
              });
            },
            // helpWidgets: state.processing || loadedMessages.last.isInitMessage()
            //     ? null
            //     : [
            //         HelpTips(
            //           onSubmitMessage: _handleSubmit,
            //           onNewChat: () => handleResetContext(context),
            //         )
            //       ],
          );
        }
        return Center(
            child:
                CircularProgressIndicator(color: customColors.themeBlueColor));
      },
    );
  }

  /// 构建 AppBar
  AppBar _buildAppBar(BuildContext context, CustomColors customColors) {
    return AppBar(
      centerTitle: true,
      elevation: 0,
      title: BlocBuilder<RoomBloc, RoomState>(
        buildWhen: (previous, current) => current is RoomLoaded,
        builder: (context, state) {
          if (state is RoomLoaded) {
            return Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                // 房间名称
                Text(
                  widget.titleName,
                  style: const TextStyle(
                      fontSize: 17, fontWeight: FontWeight.w500),
                ),
              ],
            );
          }
          return Container();
        },
      ),
      actions: [
        IconButton(
          padding: const EdgeInsets.all(16),
          icon: Image.asset('images/chat_room_qingli.png'),
          onPressed: () => _showClearDialog(),
        ),
      ],
      toolbarHeight: CustomSize.toolbarHeight,
    );
  }

  /// 提交新消息
  void _handleSubmit(
    String text, {
    messagetType = MessageType.text,
    int? index,
    bool isResent = false,
  }) async {
    if (freeModelCount != null && freeModelCount?.leftCount != null) {
      if ((AppUtil().touristLoginModel?.isVip ?? 0) == 0 &&
          freeModelCount!.leftCount == 0) {
        showVipGlobalDialog(context);
        return;
      }
    }

    //默认true
    setState(() {
      _inputEnabled.value = true;
    });

    if (selectedImageFiles.isNotEmpty) {
      final cancel = BotToast.showCustomLoading(
        toastBuilder: (cancel) {
          return const LoadingIndicator(
            message: '正在上传图片，请稍后...',
          );
        },
        allowClick: false,
      );

      try {
        final uploader = ImageUploader(widget.setting);

        for (var file in selectedImageFiles) {
          if (file.uploaded) {
            continue;
          }

          if (file.file.bytes != null) {
            final res = await uploader.base64(
              imageData: file.file.bytes,
              maxSize: 1024 * 1024,
              compressWidth: 512,
              compressHeight: 512,
            );
            file.setUrl(res);
          } else {
            final res = await uploader.base64(
              path: file.file.path!,
              maxSize: 1024 * 1024,
              compressWidth: 512,
              compressHeight: 512,
            );
            file.setUrl(res);
          }
        }
      } catch (e) {
        // ignore: use_build_context_synchronously
        showErrorMessageEnhanced(context, e);
        return;
      } finally {
        cancel();
      }
    }

    // ignore: use_build_context_synchronously
    context.read<ChatMessageBloc>().add(
          ChatMessageSendEvent(
            Message(
              Role.sender,
              text,
              user: 'me',
              ts: DateTime.now(),
              type: messagetType,
              images: selectedImageFiles
                  .where((e) => e.uploaded)
                  .map((e) => e.url!)
                  .toList(),
              like: 0,
              collection: 0,
            ),
            index: index,
            isResent: isResent,
            tempModel: 'great',
          ),
        );

    // ignore: use_build_context_synchronously
    context.read<NotifyBloc>().add(NotifyResetEvent());
    // ignore: use_build_context_synchronously
    context
        .read<RoomBloc>()
        .add(RoomLoadEvent(widget.roomId, cascading: false));
  }

  void _showClearDialog() async {
    _audioPlayerController.stop();

    showCustomTipsDialog(context, '清理记录', '是否清理聊天记录', onSubmit: (diaContext) {
      EasyLoading.show(status: '请稍等...');
      APIServer().chatRecordClear(widget.roomId).then((value) {
        context.read<RoomBloc>().add(RoomLoadEvent(widget.roomId, cascading: true));
        Future.delayed(const Duration(milliseconds: 700)).then((result) {
          EasyLoading.dismiss();
          diaContext.pop();

          context.read<ChatMessageBloc>().add(ChatMessageClearAllEvent());
          EasyLoading.showSuccess('清理成功');
        });
      }).catchError((e) {
        EasyLoading.dismiss();
      });
    });
  }
}

/// 处理消息删除事件
void handleDeleteMessage(BuildContext context, int id, {int? chatHistoryId}) {
  openConfirmDialog(
    context,
    AppLocale.confirmDelete.getString(context),
    () => context
        .read<ChatMessageBloc>()
        .add(ChatMessageDeleteEvent([id], chatHistoryId: chatHistoryId)),
    danger: true,
  );
}

/// 重置上下文
void handleResetContext(BuildContext context) {
  // openConfirmDialog(
  //   context,
  //   AppLocale.confirmStartNewChat.getString(context),
  //   () {
  context.read<ChatMessageBloc>().add(ChatMessageBreakContextEvent());
  HapticFeedbackHelper.mediumImpact();
  //   },
  // );
}

/// 清空历史消息
void handleClearHistory(BuildContext context) {
  openConfirmDialog(
    context,
    AppLocale.confirmClearMessages.getString(context),
    () {
      context.read<ChatMessageBloc>().add(ChatMessageClearAllEvent());
      showSuccessMessage(AppLocale.operateSuccess.getString(context));
      HapticFeedbackHelper.mediumImpact();
    },
    danger: true,
  );
}

/// 打开示例问题列表
void handleOpenExampleQuestion(
  BuildContext context,
  Room room,
  List<ChatExample> examples,
  Function(String text) onSubmit,
) {
  final customColors = Theme.of(context).extension<CustomColors>()!;

  openModalBottomSheet(
    context,
    (context) {
      return FractionallySizedBox(
        heightFactor: 0.8,
        child: GlassEffect(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Container(
                padding: const EdgeInsets.symmetric(
                  vertical: 10,
                ),
                child: Text(
                  AppLocale.examples.getString(context),
                  textScaleFactor: 1.2,
                ),
              ),
              Expanded(
                child: ListView.builder(
                  itemCount: examples.length,
                  itemBuilder: (context, i) {
                    return ListTile(
                      title: Container(
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(
                          horizontal: 10,
                          vertical: 10,
                        ),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(10),
                          color: customColors.chatExampleItemBackground,
                        ),
                        child: Column(
                          children: [
                            Text(
                              examples[i].title,
                              textAlign: TextAlign.center,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                color: customColors.chatExampleItemText,
                              ),
                            ),
                            if (examples[i].content != null)
                              const SizedBox(height: 5),
                            if (examples[i].content != null)
                              Text(
                                examples[i].content!,
                                textAlign: TextAlign.center,
                                overflow: TextOverflow.ellipsis,
                                maxLines: 2,
                                style: TextStyle(
                                  fontSize: 12,
                                  color: customColors.chatExampleItemText,
                                ),
                              ),
                          ],
                        ),
                      ),
                      onTap: () {
                        final controller = TextEditingController();
                        controller.text = examples[i].text;

                        openDialog(
                          context,
                          title: Text(
                            AppLocale.confirmSend.getString(context),
                            textAlign: TextAlign.left,
                            textScaleFactor: 0.8,
                          ),
                          builder: Builder(
                            builder: (context) {
                              return EnhancedTextField(
                                controller: controller,
                                maxLines: 5,
                                maxLength: 4000,
                                customColors: customColors,
                              );
                            },
                          ),
                          onSubmit: () {
                            onSubmit(controller.text.trim());
                            return true;
                          },
                          afterSubmit: () => context.pop(),
                        );
                      },
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      );
    },
  );
}

/// 构建聊天内容窗口
Widget buildSelectModeToolbars(
  BuildContext context,
  ChatPreviewController chatPreviewController,
  CustomColors customColors,
) {
  return Container(
    padding: const EdgeInsets.all(10),
    decoration: BoxDecoration(
      borderRadius: const BorderRadius.only(
        topLeft: Radius.circular(10),
        topRight: Radius.circular(10),
      ),
      color: customColors.backgroundColor,
    ),
    child: SafeArea(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          TextButton.icon(
            onPressed: () {
              var messages = chatPreviewController.selectedMessages();
              if (messages.isEmpty) {
                showErrorMessageEnhanced(
                    context, AppLocale.noMessageSelected.getString(context));
                return;
              }

              Navigator.push(
                context,
                MaterialPageRoute(
                  fullscreenDialog: true,
                  builder: (context) => ChatShareScreen(
                    messages: messages
                        .map((e) => ChatShareMessage(
                              content: e.message.text,
                              username: e.message.senderName,
                              avatarURL: e.message.avatarUrl,
                              leftSide: e.message.role == Role.receiver,
                              images: e.message.images,
                            ))
                        .toList(),
                  ),
                ),
              );
              // var messages = chatPreviewController.selectedMessages();
              // if (messages.isEmpty) {
              //   showErrorMessageEnhanced(
              //       context, AppLocale.noMessageSelected.getString(context));
              //   return;
              // }
              // var shareText = messages.map((e) {
              //   if (e.message.role == Role.sender) {
              //     return '我：\n${e.message.text}';
              //   }

              //   return '助理：\n${e.message.text}';
              // }).join('\n\n');

              // shareTo(
              //   context,
              //   content: shareText,
              //   title: AppLocale.chatHistory.getString(context),
              // );
            },
            icon: Icon(Icons.share, color: customColors.linkColor),
            label: Text(
              AppLocale.share.getString(context),
              style: TextStyle(color: customColors.linkColor),
            ),
          ),
          TextButton.icon(
            onPressed: () {
              chatPreviewController.selectAllMessage();
            },
            icon:
                Icon(Icons.select_all_outlined, color: customColors.linkColor),
            label: Text(
              AppLocale.selectAll.getString(context),
              style: TextStyle(color: customColors.linkColor),
            ),
          ),
          TextButton.icon(
            onPressed: () {
              if (chatPreviewController.selectedMessageIds.isEmpty) {
                showErrorMessageEnhanced(
                    context, AppLocale.noMessageSelected.getString(context));
                return;
              }

              openConfirmDialog(
                context,
                AppLocale.confirmDelete.getString(context),
                () {
                  final ids = chatPreviewController.selectedMessageIds.toList();
                  if (ids.isNotEmpty) {
                    context
                        .read<ChatMessageBloc>()
                        .add(ChatMessageDeleteEvent(ids));

                    showErrorMessageEnhanced(
                        context, AppLocale.operateSuccess.getString(context));

                    chatPreviewController.exitSelectMode();
                  }
                },
                danger: true,
              );
            },
            icon: Icon(Icons.delete, color: customColors.linkColor),
            label: Text(
              AppLocale.delete.getString(context),
              style: TextStyle(color: customColors.linkColor),
            ),
          ),
        ],
      ),
    ),
  );
}
